from src.pages.base_page import BasePage


class LoginPage(BasePage):

    def __init__(self, page, locators_data: dict = None):
        """
        :param page: playwright 的 page 对象
        :param locators_data: 元素定位信息，读取文件生成
        """
        super().__init__(page)
        self.locators_data = locators_data
        self.page_name = "login_page"
        self._elements_initialized = False  # 添加初始化状态标志
        # 只在提供了 locators_data 时才初始化
        if locators_data:
            self.set_locators(locators_data)

    def set_locators(self, locators_data: dict):
        """设置或更新定位器配置"""
        if not locators_data:
            raise ValueError("locators_data 不能为空")

        self.locators_data = locators_data
        self._init_elements()

    def _init_elements(self):
        """初始化页面元素"""
        # 使用安全访问方式，避免 None 异常
        self.account_input = self.locators_data.get('account_input', {}).get('selector')
        self.password_input = self.locators_data.get('password_input', {}).get('selector')
        self.login_button = self.locators_data.get('login_button', {}).get('selector')

    def navigate(self):
        self.page.goto(f'{self.base_url}g=Team&m=Login&a=index')
        '''
        self.page.wait_for_load_state("networkidle")  # 等待页面完全加载
        # === 1. 获取完整 HTML 内容（DOM 树）===
        page_content = self.page.content()
        page_evaluate = self.page.evaluate("document.documentElement.outerHTML")
        # save_dom(page_evaluate=data, page_content=html_content)
        # print(html_content)
        with open(f"{self.page_name}.json", "w", encoding="utf-8") as f:
            json.dump(page_evaluate, f, ensure_ascii=False, indent=2)
        print(f"✅ JSON 已保存到: {self.page_name}.json")

        with open(f"{self.page_name}.html", "w", encoding="utf-8") as f:
            f.write(page_content)
        print(f"✅ HTML 已保存到: {self.page_name}.html")
        '''

    def login(self, username, password):
        self.fill(self.account_input, username)
        self.fill(self.password_input, password)
        self.click(self.login_button)
